package com.pointlion.sys.mvc.admin.evaluate.paper;

import java.math.BigDecimal;
import java.util.*;

import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.pointlion.sys.interceptor.MainPageTitleInterceptor;
import com.pointlion.sys.mvc.admin.evaluate.paperbase.PaperBaseService;
import com.pointlion.sys.mvc.admin.evaluate.paperitem.PaperItemService;
import com.pointlion.sys.mvc.common.base.BaseController;
import com.pointlion.sys.mvc.admin.oa.workflow.WorkFlowService;
import com.pointlion.sys.mvc.common.model.*;
import com.pointlion.sys.mvc.common.utils.StringUtil;
import com.pointlion.sys.mvc.common.utils.UuidUtil;
import com.pointlion.sys.mvc.common.utils.Constants;
import com.pointlion.sys.mvc.admin.oa.common.OAConstants;
import com.pointlion.sys.mvc.common.utils.DateUtil;
import com.pointlion.sys.plugin.shiro.ShiroKit;
import com.pointlion.sys.plugin.shiro.ext.SimpleUser;
import net.sf.json.JSON;
import net.sf.json.JSONObject;

import static com.pointlion.sys.mvc.admin.evaluate.paper.PaperService.me;


@Before(MainPageTitleInterceptor.class)
public class PaperController extends BaseController {
	public static final PaperService service = me;
	public static WorkFlowService wfservice = WorkFlowService.me;
	/***
	 *
	 */
	public void getListPage(){
    	render("list.html");
    }
	/***
     *
     **/
    public void listData(){
    	String curr = getPara("pageNumber");
    	String pageSize = getPara("pageSize");
    	Page<Record> page = service.getPage(Integer.valueOf(curr),Integer.valueOf(pageSize));
    	renderPage(page.getList(),"",page.getTotalRow());
    }
    /***
     *
     */
    public void save(){
    	Paper o = getModel(Paper.class);
    	String pId = getPara("pId");
    	String pCode = getPara("pCode");
    	if(StrKit.notBlank(o.getId())){
    		o.update();
    	}else{
    		o.setId(UuidUtil.getUUID());
    		o.setUserId(ShiroKit.getUserId());
    		o.setCreateTime(new Date());
    		o.save();
    	}
		String[] ids = pId.split(",");
    	String[] pcs = pCode.split(",");
    	PaperItemService.me.deleteByPaperId(o.getId());
    	for(int i=0;i<ids.length;i++) {
    		PaperItem paperItem = new PaperItem();
    		PaperItem p = PaperItemService.me.getNameByid(ids[i]);
    		paperItem.setId(UuidUtil.getUUID());
    		paperItem.setBaseId(ids[i]);
    		paperItem.setParentId(p.getParentId());
    		paperItem.setPaperId(o.getId());
    		paperItem.setValue(pcs[i]);
    		paperItem.setName(p.getName());
    		paperItem.save();

		}
    	renderSuccess();
    }
	/**
	 * 发布问卷
	 */
	public void publish(){
		try {
			String id = getPara("id");
			Paper o = me.getById(id);
			o.setPaperStatus(1);
			o.update();
			renderSuccess();
		}catch (Exception e){
			renderError();
			e.printStackTrace();
		}
	}
	/**
	 * 撤回问卷
	 */
	public void reback(){
		try {
			String id = getPara("id");
			Paper o = me.getById(id);
			o.setPaperStatus(0);
			o.update();
			renderSuccess();
		}catch (Exception e){
			renderError();
			e.printStackTrace();
		}
	}
	/***
     *
     */
    public void getEditPage(){
    	String id = getPara("id");
    	if(StrKit.notBlank(id)){
    		Paper o = service.getById(id);
    		setAttr("o", o);
    	}else{
    		SysUser user = SysUser.dao.findById(ShiroKit.getUserId());
    		SysOrg org = SysOrg.dao.findById(user.getOrgid());
    		setAttr("user", user);
    		setAttr("org", org);
    	}
		List<PaperItem> list = PaperItemService.me.getByPaperId(id);
		String ids = "";
		String names = "";
		String code = "";
    	if(list.size()>0) {
			for (PaperItem i : list) {
				ids += "," + i.getBaseId();
				names += "," + i.getName();
				code +=","+i.getValue();
			}
			if (StrKit.notBlank(ids)) {
				ids = ids.substring(1);
			}
			if (StrKit.notBlank(names)) {
				names = names.substring(1);
			}
			if (StrKit.notBlank(code)) {
				code = code.substring(1);
			}
		}
    	setAttr("pId",ids);
    	setAttr("pName",names);
    	setAttr("pCode",code);
    	setAttr("formModelName",StringUtil.toLowerCaseFirstOne(Paper.class.getSimpleName()));//ģ������
    	render("edit.html");
    }
    /***
     *
     * @throws Exception
     */
    public void delete() throws Exception{
		String ids = getPara("ids");
		service.deleteByIds(ids);
    	renderSuccess("删除成功!");
    }
	/**
	 *
	 */
	public void getSelectOneItemPage(){
		render("selectOneItem.html");
	}
	public void getDataByPaperid(){
		String paperid = getPara("paperid");
		List<Paper> list = Paper.dao.getDataByPaperid(paperid);
		renderJson(list);
	}
	/**************************************************************************/
	private String pageTitle = "评价管理";//模块页面标题
	private String breadHomeMethod = "getListPage";//面包屑首页方法

	public Map<String,String> getPageTitleBread() {
		Map<String,String> pageTitleBread = new HashMap<String,String>();
		pageTitleBread.put("pageTitle", pageTitle);
		pageTitleBread.put("breadHomeMethod", breadHomeMethod);
		return pageTitleBread;
	}
	//设计问卷
	public void designPaper() {
		String id = getPara("id");
		Paper o = me.getById(id);
		setAttr("o",o);
		String write = getPara("write");
		List<PaperItem> paperItems = PaperItemService.me.getItems(id);
		for(PaperItem a : paperItems){
			List<PaperItem> blist = PaperItemService.me.getListByPid(a.getBaseId(),id);//下面的指标
			a.setChildren(blist);
		}
		setAttr("paperItems",paperItems);
		if("write".equals(write)){
			setAttr("back","/admin/paper/showPaper");
			render("writePaper.html");
		}else{
			render("designPaper.html");
		}
	}

	/**
	 * 用户问卷展示
	 */
	public void showPaper(){
		//获得所有已发布的问卷
		List<Paper> paperlist = me.getPubPaper();
		setAttr("paperlist",paperlist);
		render("UserPaper.html");
	}

	public void saveUserPaper(){
		try {
			//SimpleUser user = ShiroKit.getLoginUser();
			String param = getPara("formData");
			String[] temp;
			//代码还挺规范，不用魔法值了，嘻嘻嘻
			//阿里代码规范建议，不写行尾注释。。。
			String delimeter = "&"; //指定分割字符
			temp = param.split(delimeter); //分割字符

		/*for (int i=1;i<temp.length; i++) {
			PaperUser paperUser = new PaperUser();
			paperUser.setId(UuidUtil.getUUID());
			String paperid = temp[0].substring(9,temp[0].length());
			paperUser.setPaperId(paperid);
			String baseid = temp[i].split("=")[0];
			String pValue = temp[i].split("=")[1];
			paperUser.setBaseId(baseid.split("que")[1]);
			//对象中既然已经有baseId，直接取出来，为了获得name和parent_id
			PaperBase b = PaperBase.dao.findFirst("select * from paper_base where id = '"+paperUser.getBaseId()+"'");
			paperUser.setName(b.getName());
			paperUser.setParentId(b.getParentId());
			paperUser.setValue(pValue);
			//插入用户id
			paperUser.setCreateId(ShiroKit.getUserId());
			paperUser.save();
		}*/

			//为了提高插入效率，批量插入
			//纵向存入多条数据
			List<PaperUser> paperUserList = new ArrayList<PaperUser>();

			String paperid = temp[0].substring(9, temp[0].length());
			for (int i = 1; i < temp.length; i++) {
				PaperUser paperUser = new PaperUser();
				paperUser.setId(UuidUtil.getUUID());
				paperUser.setPaperId(paperid);
				String baseid = temp[i].split("=")[0];
				String pValue = temp[i].split("=")[1];
				paperUser.setBaseId(baseid.split("que")[1]);
				//对象中既然已经有baseId，直接取出来，为了获得name和parent_id
				PaperBase b = PaperBase.dao.findFirst("select * from paper_base where id = '" + paperUser.getBaseId() + "'");
				paperUser.setName(b.getName());
				paperUser.setParentId(b.getParentId());
				paperUser.setValue(pValue);
				//小数和整数相乘先转换
				BigDecimal Code = new BigDecimal(b.getCode());
				BigDecimal Value = new BigDecimal(pValue);
				paperUser.setTotalValue(String.valueOf(Code.multiply(Value)));
				//插入用户id
				paperUser.setCreateId(ShiroKit.getUserId());
				paperUser.setCreateTime(new Date());
				paperUserList.add(paperUser);
			}
			Db.batchSave(paperUserList, 1000);

			//再把该问卷中的#root （主题也保存），为了历史查看详情使用
			//获得该问卷下，所有父级项
			List<PaperItem> list = PaperItemService.me.getRootList(paperid);
			for(PaperItem p : list){
				PaperUser paperUser = new PaperUser();
				paperUser.setId(UuidUtil.getUUID());
				paperUser.setPaperId(paperid);
				paperUser.setBaseId(p.getBaseId());
				paperUser.setName(p.getName());
				paperUser.setParentId(p.getParentId());
				paperUser.setCreateId(ShiroKit.getUserId());
				paperUser.setCreateTime(new Date());
				paperUser.save();
			}

			//别忘啦 填写问卷次数+1哦~
			Paper p = PaperService.me.getById(paperid);
			p.setPaperCount(p.getPaperCount()+1);
			p.update();

			//将json字符串转换为json对象
			renderSuccess("保存成功！");
		}catch (Exception e){
			//前台有错误提醒，故加上try catch
			renderError("保存失败！");
			e.printStackTrace();
		}
	}

	/**
	 * 历史问卷展示
	 */
	public void showHistroyPaper(){
		//获得用户的历史问卷
		List<Paper> paperlist = me.getHistroyPaper();
		setAttr("Historypaperlist",paperlist);
		render("histroyPaper.html");
	}


	/**
	 * 根据id 用户查看历史问卷
	 */
	public void viewHistroyPaper() {
		String id = getPara("id");
		Paper o = me.getById(id);
		setAttr("o",o);
		List<PaperItem> paperItems = PaperItemService.me.getHistoryItems(id);
		for(PaperItem a : paperItems){
			List<PaperItem> blist = PaperItemService.me.getHistroyListByPid(a.getBaseId(),id);//下面的指标
			a.setChildren(blist);
		}
		setAttr("paperItems",paperItems);
		render("viewHistroyPaper.html");
	}

}